<template>
  <div class="student-grades">
    <a-card title="学生成绩">
      <!-- 搜索表单 -->
      <a-form layout="inline" class="search-form">
        <a-form-item label="学号">
          <a-input 
            v-model:value="searchForm.student_id" 
            placeholder="请输入学号" 
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item label="姓名">
          <a-input 
            v-model:value="searchForm.student_name" 
            placeholder="请输入姓名" 
            style="width: 120px"
          />
        </a-form-item>
        <a-form-item label="专业">
          <a-input 
            v-model:value="searchForm.major" 
            placeholder="请输入专业" 
            style="width: 120px"
          />
        </a-form-item>
        <a-form-item label="年级">
          <a-input 
            v-model:value="searchForm.grade_year" 
            placeholder="请输入年级" 
            style="width: 100px"
          />
        </a-form-item>
        <a-form-item label="班级">
          <a-input 
            v-model:value="searchForm.class_name" 
            placeholder="请输入班级" 
            style="width: 120px"
          />
        </a-form-item>
        <a-form-item label="学年">
          <a-select 
            v-model:value="searchForm.time" 
            placeholder="请选择" 
            style="width: 100px" 
            allow-clear
          >
            <a-select-option :value="2025">2025</a-select-option>
            <a-select-option :value="2024">2024</a-select-option>
            <a-select-option :value="2023">2023</a-select-option>
            <a-select-option :value="2022">2022</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 成绩表格 -->
      <a-table 
        :columns="dynamicColumns" 
        :data-source="dataSource" 
        :loading="loading"
        :pagination="pagination"
        :scroll="{ x: 'max-content' }"
        bordered
        size="small"
        style="margin-top: 20px"
      >
        <template #bodyCell="{ column, record }">
          <!-- 学号列 -->
          <template v-if="column.key === 'student_id'">
            <span style="font-weight: 500">{{ record.student_id }}</span>
          </template>
          
          <!-- 平均分列 -->
          <template v-else-if="column.key === 'avg_grade'">
            <a-tag :color="record.avg_grade >= 60 ? 'blue' : 'red'">
              {{ record.avg_grade }}
            </a-tag>
          </template>
          
          <!-- 及格率列 -->
          <template v-else-if="column.key === 'pass_rate'">
            <span :style="{ color: record.pass_rate >= 80 ? '#3f8600' : '#cf1322' }">
              {{ record.pass_rate }}%
            </span>
          </template>
          
          <!-- 课程成绩列 -->
          <template v-else-if="column.dataIndex && column.dataIndex.startsWith('course_')">
            <a-tag v-if="record[column.dataIndex]" :color="Number(record[column.dataIndex]) >= 60 ? 'green' : 'red'">
              {{ record[column.dataIndex] }}
            </a-tag>
            <span v-else style="color: #ccc">-</span>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { gradeAPI } from '@/api/grade'
import type { GradeDetail } from '@/api/grade'

const loading = ref(false)
const dataSource = ref<any[]>([])
const allCourses = ref<string[]>([]) // 所有课程名称

const searchForm = reactive({
  student_id: '',
  student_name: '',
  major: '',
  grade_year: '',
  class_name: '',
  time: undefined as number | undefined
})

const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 30,
  showTotal: (total: number) => `共 ${total} 个学生`,
  onChange: (page: number, pageSize: number) => {
    pagination.value.current = page
    pagination.value.pageSize = pageSize
    loadData()
  }
})

// 动态生成表格列
const dynamicColumns = computed(() => {
  const baseColumns = [
    { title: '学号', dataIndex: 'student_id', key: 'student_id', width: 120, fixed: 'left' },
    { title: '姓名', dataIndex: 'student_name', key: 'student_name', width: 100, fixed: 'left' },
    { title: '专业', dataIndex: 'major', key: 'major', width: 150 },
    { title: '年级', dataIndex: 'grade_year', key: 'grade_year', width: 80 },
    { title: '班级', dataIndex: 'class_name', key: 'class_name', width: 100 }
  ]
  
  // 添加课程列
  const courseColumns = allCourses.value.map(courseName => ({
    title: courseName,
    dataIndex: `course_${courseName}`,
    key: `course_${courseName}`,
    width: 80,
    align: 'center'
  }))
  
  const statColumns = [
    { title: '平均分', dataIndex: 'avg_grade', key: 'avg_grade', width: 80, align: 'center' },
    { title: '及格率', dataIndex: 'pass_rate', key: 'pass_rate', width: 80, align: 'center' }
  ]
  
  return [...baseColumns, ...courseColumns, ...statColumns]
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await gradeAPI.getStudentMatrix({
      student_id: searchForm.student_id || undefined,
      student_name: searchForm.student_name || undefined,
      major: searchForm.major || undefined,
      grade_year: searchForm.grade_year || undefined,
      class_name: searchForm.class_name || undefined,
      time: searchForm.time,
      page: pagination.value.current,
      page_size: pagination.value.pageSize
    })

    if (res.data.code === 200) {
      // 设置课程列表
      allCourses.value = res.data.data.courses || []
      
      // 设置学生数据
      dataSource.value = res.data.data.results || []
      
      // 设置分页
      pagination.value.total = res.data.data.count || 0
    } else {
      message.error(res.data.message || '加载失败')
    }
  } catch (error: any) {
    message.error('加载数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.student_id = ''
  searchForm.student_name = ''
  searchForm.major = ''
  searchForm.grade_year = ''
  searchForm.class_name = ''
  searchForm.time = undefined
  dataSource.value = []
  allCourses.value = []
  pagination.value.current = 1
}

// 页面加载时自动加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}

:deep(.ant-table) {
  font-size: 12px;
}

:deep(.ant-table-cell) {
  padding: 8px 4px;
}
</style>
